package com.heima.comment.serivce.impl;

import com.heima.comment.client.UserFeignClient;
import com.heima.comment.dto.*;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApCommentLike;
import com.heima.comment.serivce.IApCommentService;
import com.heima.comment.vo.ApCommentVo;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.dto.UserThreadLocalUtil;
import com.heima.common.enums.AppHttpCodeEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 评论业务层实现类
 *
 * @Name : ApCommentServiceImpl
 * @Author : WuQiang
 * @Date : 2022-10-16 20:36
 * @Description : 评论业务层实现类
 */
@Service
public class ApCommentServiceImpl implements IApCommentService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 保存评论
     *
     * @param dto dto
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult save(CommentSaveDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //获取当前登录用户
        User user = UserThreadLocalUtil.get();
        //未登录或者游客 不能评论
        Integer userId = user.getUserId();
        if (user == null || userId == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ResponseResult responseResult = userFeignClient.getById(userId);
        if (responseResult.getCode() == 0) {
            ApUser apUser = (ApUser) responseResult.getData();
            ApComment apComment = new ApComment();
            apComment.setUserId(userId);
            apComment.setUserName(apUser.getName());
            apComment.setImage(apUser.getImage());
            apComment.setArticleId(dto.getArticleId());
            apComment.setContent(dto.getContent());
            apComment.setLikes(0);
            apComment.setRepay(0);
            apComment.setCreatedTime(new Date());
            //保存到MongoDB
            mongoTemplate.save(apComment);
            // TODO: 2022/10/22  往kafka发送消息
      
        }

        return ResponseResult.okResult();
    }

    /**
     * 查询评论列表
     *
     * @param dto dto
     * @return {@code ResponseResult}
     */
    @Override
    public ResponseResult load(CommentDto dto) {
        //参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        Integer size = dto.getSize();
        if (size == null || size == 0) {
            size = 20;
        }

        //查询条件  articleId = "" and createTime <= minDate
        Criteria criteria = Criteria
                .where("articleId").is(dto.getArticleId())
                .and("createdTime").lte(dto.getMinDate());
        Query query = new Query(criteria);
        //分页
        query.limit(size);
        //排序
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
        //查询当前登录用户
        User user = UserThreadLocalUtil.get();
        if (user != null && user.getUserId() != 0) {
            //创建返回结果集合对象
            ArrayList<ApCommentVo> apCommentVos = new ArrayList<>();
            //查询redis中的标记
            for (ApComment apComment : apComments) {
                ApCommentVo apCommentVo = new ApCommentVo();
                BeanUtils.copyProperties(apComment, apCommentVo);
                Boolean key = redisTemplate.hasKey("comment_like:" + user.getUserId() + ":" + apComment.getId());
                apCommentVo.setOperation(key ? 0 : 1);
                apCommentVos.add(apCommentVo);
            }
            return ResponseResult.okResult(apCommentVos);
        }
        //游客直接查询所有信息返回
        return ResponseResult.okResult(apComments);
    }

    /**
     * 保存评论点赞
     *
     * @param dto dto
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult like(CommentLikeDto dto) {
        //参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //登录后才能点赞评论
        User user = UserThreadLocalUtil.get();
        if (user == null || user.getUserId() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //组装数据
        ApCommentLike apCommentLike = new ApCommentLike();
        // apCommentLike.setId();  主键自增
        apCommentLike.setUserId(user.getUserId());
        apCommentLike.setCommentId(dto.getCommentId());
        apCommentLike.setOperation(dto.getOperation());
        apCommentLike.setCreateTime(new Date());
        mongoTemplate.save(apCommentLike);

        //评论表点赞数加1  update ap_comment set likes = likes + 1  where _id = ?
        Query query = new Query(Criteria.where("_id").is(dto.getCommentId()));
        Update update = new Update();
        if (dto.getOperation() == 0) {
            //点赞
            update.inc("likes", 1);
            //当前用户点完赞后往redis中添加一个标记
            redisTemplate.boundValueOps("comment_like:" + user.getUserId() + ":" + dto.getCommentId())
                    .set("");
        } else {
            //取消点赞
            update.inc("likes", -1);
            //取消点赞从redis中删除这个标记
            redisTemplate.delete("comment_like:" + user.getUserId() + ":" + dto.getCommentId());
        }
        mongoTemplate.updateFirst(query, update, ApComment.class);
        return ResponseResult.okResult();
    }


}
